package com.maxmlr.music.system.service.impl;

import com.maxmlr.music.admin.entity.User;
import com.maxmlr.music.admin.service.UserService;
import com.maxmlr.music.common.base.BaseServiceImpl;
import com.maxmlr.music.common.exception.XmlrException;
import com.maxmlr.music.system.dao.TaskMapper;
import com.maxmlr.music.system.entity.Task;
import com.maxmlr.music.system.param.TaskParam;
import com.maxmlr.music.system.service.TaskService;
import com.maxmlr.music.system.service.transfer.TaskTransfer;
import com.maxmlr.music.system.task.factory.QuartzManager;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author max
 * @version 1.0
 * @ClassName TaskServiceImpl
 * @Description 服务实现类
 * @Copyright Copyright (c) 2020: www.maxmlr.com.
 * @since 2020-06-14
 */
@Slf4j
@Service
public class TaskServiceImpl extends BaseServiceImpl<TaskMapper, Task> implements TaskService {

    public static final String STATUS_RUNNING = "1";
    public static final String STATUS_NOT_RUNNING = "0";

    @Autowired
    private QuartzManager quartzManager;

    @Autowired
    private TaskTransfer taskTransfer;

    @Autowired
    private UserService userService;


    @Override
    public boolean changeStatus(TaskParam param) throws SchedulerException {
        Task task = getById(param.getId());
        if (task == null) {
            throw new XmlrException("任务不存在");
        }
        if (STATUS_RUNNING.equals(param.getJobStatus())) {
            quartzManager.deleteJob(task);
            task.setJobStatus(STATUS_NOT_RUNNING);
        } else if (STATUS_NOT_RUNNING.equals(param.getJobStatus())) {
            task.setJobStatus(STATUS_RUNNING);
            quartzManager.addJob(task);
        }
        return updateById(task);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveParam(TaskParam param) {
        User adminUser = userService.getAdminUser();
        Task task = taskTransfer.po2Task(param, adminUser);
        return save(task);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateParam(TaskParam param) {
        Task task = getById(param.getId());
        if (task == null) {
            throw new XmlrException("任务不存在");
        }
        User adminUser = userService.getAdminUser();
        taskTransfer.fullTask(task, param, adminUser);
        return updateById(task);
    }


}
